package megrez.boot.autoconfigure.minio;

import java.net.InetSocketAddress;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import megrez.boot.autoconfigure.minio.MinioProperties.Connection;
import megrez.boot.autoconfigure.minio.MinioProperties.Proxy;
import megrez.boot.autoconfigure.minio.MinioProperties.Server;
import okhttp3.OkHttpClient;

/**
 * MinIO Client自动配置
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@Slf4j
@Configuration
@ConditionalOnClass(MinioClient.class)
@EnableConfigurationProperties(MinioProperties.class)
public class MinioAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public MinioClient minioClient(MinioProperties properties, ObjectProvider<MinioConfigurer> configurers) {

        final Server server = properties.getServer();
        final Connection connection = properties.getConnection();
        final Proxy proxy = properties.getProxy();

        log.info("Initializing MinioClient [{}:{}]", server.getEndpoint(), server.getPort());

        final MinioClient.Builder builder = MinioClient.builder()
                .endpoint(server.getEndpoint(), server.getPort(), server.isSecure())
                .credentials(server.getAccessKey(), server.getSecretKey());

        if (StringUtils.hasText(proxy.getHost())) {
            log.info("Http proxy enabled [{}:{}]}", proxy.getHost(), proxy.getPort());
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .proxy(new java.net.Proxy(java.net.Proxy.Type.HTTP,
                            new InetSocketAddress(proxy.getHost(), proxy.getPort())))
                    .build();
            builder.httpClient(okHttpClient);
        }

        // 自定义配置处理
        configurers.forEach(configurer -> configurer.configure(builder));

        MinioClient minioClient = builder.build();
        minioClient.setTimeout(
                connection.getConnectTimeout().toMillis(),
                connection.getWriteTimeout().toMillis(),
                connection.getReadTimeout().toMillis());
        return minioClient;
    }

    @Bean
    @ConditionalOnMissingBean
    public MinioObjectClient minioObjectClient(MinioClient minioClient) {
        return new MinioObjectClient(minioClient);
    }

    @Bean
    @ConditionalOnMissingBean
    public MinioBucketClient minioBucketClient(MinioClient minioClient) {
        return new MinioBucketClient(minioClient);
    }
}
